// 终端类型分类
const deviceTypeList = [
    { label: '气象', value: [3, 20, 37, 52, 57, 63] },
    { label: '水质', value: [85] },
    { label: '土壤', value: [35] },
    { label: '病害', value: [39] },
    { label: '虫害', value: [1, 49, 56, 61, 62, 64, 72] }
];
const pageConf = {
    data() {
        return {
            // 地图实例
            exampleMap: null,
            // 设备列表
            deviceData: [],
            // 设备标记列表
            markerList: [],
            // 点位搜索值
            markerSearchValue: "",
            // 项目列表
            projectList: [],
            // 项目Id列表
            projectIds: [],
            // 项目点位列表
            projectMarkerList: [],
            // 当前点击项目点位
            currentProjectMarker: null,
            // 点位数据
            markerData: {
                visible: false,
                params: {},
            },
            // 信息窗体实例
            infoWindow: null,
            // 信息窗体信息
            infoWindowInfo: {},


            // 左上设备情况分析数据
            equipmentSituationData: [],
            // 设备情况分析加载
            equipmentLoading: false,


            // 共预警次数
            problemHandleTotal: 0,

        }
    },
    computed: {
        /**
         * 地图图层数组
         */
        curMapLayer() {
            const KEY = "4caf91d8465b13654a44b4f71c35e7e0";
            let xyzTileLayer = new AMap.TileLayer({ //天地图底图图块取图地址
                getTileUrl: `https://t{0,1,2,3,4,5,6,7}.tianditu.gov.cn/DataServer?T=img_w&tk=${KEY}&x=[x]&y=[y]&l=[z]`,
                zIndex: 2
            });
            let wordTileLayer = new AMap.TileLayer({    //天地图文字标注图块取图地址
                getTileUrl: `https://t{0,1,2,3,4,5,6,7}.tianditu.gov.cn/DataServer?T=cia_w&tk=${KEY}&x=[x]&y=[y]&l=[z]`,
                zIndex: 3
            });
            return [xyzTileLayer, wordTileLayer];
        },
        /**
         * 当前选中的项目名称
         */
        curProjectName() {
            let obj = this.projectList.find(el => el.project_id == this.markerSearchValue);
            return obj && obj.project_name || ""
        }
    },
    watch: {
        // 右上搜索改变
        markerSearchValue(value) {
            this.mapLandDeviceSet([], 2);
            if (value === "") {
                this.getProjectTerminalList();
                if (this.currentProjectMarker) {
                    let row = this.currentProjectMarker.getExtData();
                    let content = `
                            <div class="device-marker" title="${row.name || ''}"><img src="${row.icon}" alt="">
                                <div class="dot-badge" style="display: ${row.num > 0 ? '' : 'none'}">${row.num}</div>
                                <img class="alarm-img" style="display: ${row.status == 2 ? '' : 'none'}" src="./img/Alarm.png" alt="">
                            </div>
                        `
                    this.currentProjectMarker.setContent(content)
                    this.currentProjectMarker.setzIndex(99);
                }
                return
            }
            let markerList = this.exampleMap.getAllOverlays('marker');
            markerList.forEach(item => {
                let row = item.getExtData();
                if (row.projectId == value) {
                    this.resetMarkerStyle(item)
                }
            })
        }
    },
    methods: {
        /**
        * 初始化地图
        */
        initMap() {
            let curMapLayer = this.curMapLayer;
            var map = new AMap.Map('map-container', {
                resizeEnable: true,
                zoom: 7.99,
                viewMode: "2D", // 地图模式
                jogEnable: true, // 是否开启缓动效果
                defaultCursor: "grab",
                animateEnable: false,
                // center: [128.40394, 48.69221],
                layers: curMapLayer,
                // layers: [
                //     // 卫星
                //     new AMap.TileLayer.Satellite(),
                //     // 路网
                //     // new AMap.TileLayer.RoadNet()
                // ],
            });
            this.getAreaList();

            let dom = this.$refs.infoWindow;
            let infoWindow = new AMap.InfoWindow({
                content: dom,
                anchor: 'top-center',
                offset: [0, 30]
            });
            this.infoWindow = infoWindow;
            map.on('click', (e) => {
                if (infoWindow) infoWindow.close();
                this.mapLandDeviceSet([], 2);
            });
            this.exampleMap = map;

            // this.getDeviceList();
            this.getProjectList();
            window.onresize = function () {
                map.resize();
            }
        },
        /**
         * 重置点位样式
         */
        resetMarkerStyle(marker) {
            if (this.currentProjectMarker) {
                let row = this.currentProjectMarker.getExtData();
                let content = `
                        <div class="device-marker" title="${row.name || ''}"><img src="${row.icon}" alt="">
                            <div class="dot-badge" style="display: ${row.num > 0 ? '' : 'none'}">${row.num}</div>
                            <img class="alarm-img" style="display: ${row.status == 2 ? '' : 'none'}" src="./img/Alarm.png" alt="">
                        </div>
                    `
                this.currentProjectMarker.setContent(content)
                this.currentProjectMarker.setzIndex(99);
            }
            let row2 = marker.getExtData();
            let content = `
                        <div class="device-marker device-marker-active" title="${row2.name || ''}"><img src="${row2.icon}" alt="">
                            <div class="dot-badge" style="display: ${row2.num > 0 ? '' : 'none'}">${row2.num}</div>
                            <img class="alarm-img" style="display: ${row2.status == 2 ? '' : 'none'}" src="./img/Alarm.png" alt="">
                        </div>
                    `
            marker.setContent(content);
            marker.setzIndex(999);
            this.currentProjectMarker = marker;
            this.markerSearchValue = row2.projectId;

            this.getProjectTerminalList();
        },
        /**
         * 地图地块设备设置
         */
        mapLandDeviceSet(data, type) {
            if (type == 2 && this.markerList.length) {
                this.exampleMap.remove(this.markerList);
                this.markerList = [];
            }
            if (!data.length) {
                this.projectMarkerList.forEach(item => {
                    item.show();
                })
                this.exampleMap.setFitView(this.projectMarkerList, false, [250, 350, 350, 350]);
                return
            }
            let markerArr = []
            data.forEach(item => {
                if (item.longitude && item.latitude) {
                    let lng = parseFloat(item.longitude), lat = parseFloat(item.latitude)
                    if (item.mapLayer == 1) {
                        const wgsLngLat = GPS.gcj_decrypt_exact(lat, lng);
                        lng = wgsLngLat.lon;
                        lat = wgsLngLat.lat;
                    }
                    let icon = item.icon, content = "";
                    if (type == 3) {
                        content = `
                            <div class="device-marker" title="${item.name || ''}"><img src="${icon}" alt="">
                                <div class="dot-badge" style="display: ${item.num > 0 ? '' : 'none'}">${item.num}</div>
                                <img class="alarm-img" style="display: ${item.status == 2 ? '' : 'none'}" src="./img/Alarm.png" alt="">
                            </div>
                        `
                    } else {
                        content = '<div class="device-marker" title="' + (item.name || '') + '"><img src="' + icon + '" alt=""></div>'
                    }
                    let marker = new AMap.Marker({
                        position: new AMap.LngLat(lng, lat),
                        title: item.name,
                        extData: { types: 'device', ...item },
                        content: content,
                        offset: new AMap.Pixel(0, 0),
                        anchor: "center",
                        zIndex: type == 2 ? 1000 : 99
                    })
                    markerArr.push(marker)
                }
            })
            let _this = this;
            markerArr.forEach(item => {
                item.on("click", function (e) {
                    let row = e.target.getExtData();
                    if (type === 2) {
                        // terminalPageRedirect(row.station_id, row.terminal_id, row.terminal_serial, row.terminal_type);

                        _this.markerData.visible = true;
                        _this.markerData.params = item.getExtData();
                        _this.markerData.params.project_name = _this.curProjectName;
                    } else {
                        if (_this.infoWindow) _this.infoWindow.close();
                        _this.resetMarkerStyle(item);
                    }
                });
                item.on("mouseover", function (e) {
                    let row = e.target.getExtData();
                    if (type == 3) {
                        _this.infoWindowInfo = row;
                        _this.getProjectDetail(row, row.term_list)
                    }
                });
                item.on("mouseout", function (e) {
                    if (_this.infoWindow) _this.infoWindow.close();
                });
            });
            this.exampleMap.add(markerArr);
            if (type != 1) {
                this.exampleMap.setFitView(markerArr, false, [250, 350, 350, 350]);
                this.exampleMap.setStatus({
                    animateEnable: true
                });
                if (type == 2) {
                    this.markerList = markerArr;
                    this.projectMarkerList.forEach(item => {
                        item.hide();
                    })
                }
            }
            if (type == 3) {
                this.projectMarkerList = markerArr;
            }

        },
        /**
         * 获取项目详情
         */
        getProjectDetail2(row, type) {
            let params = { projectId: row.project_id };
            tpHttp.post(this, "action=com.top.local.hsfpl.project.getTermListByProject", { param: JSON.stringify(params) }, (data, code, message) => {
                if (code == 0 && data && data.length) {
                    if (type == 1) {
                        let markerArr = [], markerArr2 = data.map(item => item.terminalId), markerArr3 = [];
                        markerArr = this.deviceData.filter(item => {
                            return markerArr2.includes(item.terminal_id);
                        });
                        this.mapLandDeviceSet(markerArr, 2);
                    } else {
                        this.mapLandDeviceSet([], 2)
                    }
                } else {
                    this.mapLandDeviceSet([], 2);
                }
            })
        },
        getProjectDetail(row, data, type) {
            if (data && data.length) {
                let res = data.map(item => {
                    item.terminal_type = item.terminalType;
                    return item;
                });
                const { qxz, sq, insect, monitor, spore, waterquality, mq } = TERMINAL_TYPE_MAP;
                // 气象设备列表
                let qxzTerminalList = res.filter(item => qxz.value.includes(item.terminal_type)),
                    // 墒情设备列表
                    sqTerminalList = res.filter(item => sq.value.includes(item.terminal_type)),
                    // 虫情设备列表
                    insectTerminalList = res.filter(item => insect.value.includes(item.terminal_type)),
                    // 监控设备列表
                    monitorTerminalList = res.filter(item => monitor.value.includes(item.terminal_type)),
                    // 病害设备列表
                    diseaseTerminalList = res.filter(item => spore.value.includes(item.terminal_type)),
                    // 水质设备列表
                    waterqualityTerminalList = res.filter(item => waterquality.value.includes(item.terminal_type)),
                    // 苗情设备列表
                    mqTerminalList = res.filter(item => mq.value.includes(item.terminal_type));
                let deviceData = [
                    {
                        name: "气象设备",
                        nums: qxzTerminalList.length,
                        onlineNum: qxzTerminalList.filter(item => item.online == 1).length,
                        offLineNum: qxzTerminalList.filter(item => item.online == 0).length,
                    },
                    {
                        name: "墒情设备",
                        nums: sqTerminalList.length,
                        onlineNum: sqTerminalList.filter(item => item.online == 1).length,
                        offLineNum: sqTerminalList.filter(item => item.online == 0).length,
                    },
                    {
                        name: "虫情设备",
                        nums: insectTerminalList.length,
                        onlineNum: insectTerminalList.filter(item => item.online == 1).length,
                        offLineNum: insectTerminalList.filter(item => item.online == 0).length,
                    },
                    {
                        name: "监控设备",
                        nums: monitorTerminalList.length,
                        onlineNum: monitorTerminalList.filter(item => item.online == 1).length,
                        offLineNum: monitorTerminalList.filter(item => item.online == 0).length,
                    },
                    {
                        name: "病害设备",
                        nums: diseaseTerminalList.length,
                        onlineNum: diseaseTerminalList.filter(item => item.online == 1).length,
                        offLineNum: diseaseTerminalList.filter(item => item.online == 0).length,
                    },
                    {
                        name: "水质设备",
                        nums: waterqualityTerminalList.length,
                        onlineNum: waterqualityTerminalList.filter(item => item.online == 1).length,
                        offLineNum: waterqualityTerminalList.filter(item => item.online == 0).length,
                    },
                    {
                        name: "苗情设备",
                        nums: mqTerminalList.length,
                        onlineNum: mqTerminalList.filter(item => item.online == 1).length,
                        offLineNum: mqTerminalList.filter(item => item.online == 0).length,
                    }
                ];
                this.$set(this.infoWindowInfo, 'deviceData', deviceData);
            } else {
                this.infoWindowInfo.deviceData = [];
            }
            this.$nextTick(() => {
                this.infoWindow.open(this.exampleMap, [row.longitude, row.latitude]);
            })
        },
        /**
         * 获取设备列表
         */
        getDeviceList() {
            let params = { "projectId": "" };
            tpHttp.post(this, "action=com.top.hsf.field.monitor.findTerminalList", { param: JSON.stringify(params) }, (data, code, messsage) => {
                if (code == 0 && data && data.length) {
                    let res = data;
                    data.map(item => {
                        item.longitude = item.longitude || item.sta_lng;
                        item.latitude = item.latitude || item.sta_lat;
                        item.name = item.terminal_name;
                        item.icon = getTerminalInfo(item.terminal_type)?.markIcon1;
                        return item;
                    });
                    this.deviceData = data;
                } else {
                    this.deviceData = [];
                }
            })
        },
        /**
         * 获取项目列表
         */
        getProjectList() {
            let params = { "isGetTerm": true };
            tpHttp.post(this, "action=com.top.local.hsfpl.project.findProjectListBy", { param: JSON.stringify(params) }, (data, code, messsage) => {
                if (code == 0 && data && data.length) {
                    this.projectList = data.map(item => {
                        item.icon = "./img/xmtb.png";
                        item.name = item.project_name;
                        item.projectId = item.project_id;
                        item.num = item.term_list && item.term_list.length || 0;
                        return item;
                    });
                    this.mapLandDeviceSet(this.projectList, 3);
                    this.getProjectTerminalList();
                } else {
                    this.projectList = [];
                }
            })
        },
        /**
         * 获取项目下的终端列表
         */
        getProjectTerminalList() {
            this.equipmentLoading = true;
            let projectIds = this.projectList.map(item => item.projectId);
            if (this.markerSearchValue !== "") {
                projectIds = [this.markerSearchValue];
            }
            this.projectIds = projectIds;
            let params = { "projectIds": projectIds };
            tpHttp.post(this, "action=com.top.local.hsfpl.operationMonitorScreen.getTermListByProjectIds", { param: JSON.stringify(params) }, (data, code, message) => {
                if (code == 0 && data && data.length) {
                    data.map(item => {
                        let obj = deviceTypeList.find(el => el.value.includes(item.terminal_type));
                        item.terminalTypeName = obj?.label || '其他';
                    });
                    this.equipmentSituationData = data;
                    let equipmentSituationData = [], multiple = 1;
                    let onlineNum = data.filter(item => item.status == 1).length,
                        offLineNum = data.filter(item => item.status == 0).length,
                        warnNum = data.filter(item => item.status == 2).length;
                    if (onlineNum > 100 || offLineNum > 100 || warnNum > 100) {
                        onlineNum = onlineNum / 10;
                        offLineNum = offLineNum / 10;
                        warnNum = warnNum / 10;
                        multiple = 10;
                    } else if (onlineNum > 1000 || offLineNum > 1000 || warnNum > 1000) {
                        onlineNum = onlineNum / 100;
                        offLineNum = offLineNum / 100;
                        warnNum = warnNum / 100;
                        multiple = 100;
                    } else if (onlineNum > 10000 || offLineNum > 10000 || warnNum > 10000) {
                        onlineNum = onlineNum / 1000;
                        offLineNum = offLineNum / 1000;
                        warnNum = warnNum / 1000;
                        multiple = 1000;
                    }
                    equipmentSituationData = [
                        {
                            name: '正常', value: onlineNum, itemStyle: { color: '#309bff', opacity: 0.3 }
                        },
                        {
                            name: '离线', value: offLineNum, itemStyle: { color: '#dcdcdc', opacity: 0.3 }
                        }, {
                            name: '预警', value: warnNum, itemStyle: { color: '#fb9e42', opacity: 0.3 }
                        }]
                    this.$nextTick(() => {
                        initEquipmentSituationAnalysisPie(equipmentSituationData, multiple);
                    });
                    if (this.markerSearchValue !== "") {
                        let markerArr = [];
                        markerArr = data.map(item => {
                            item.longitude = item.longitude || item.sta_lng;
                            item.latitude = item.latitude || item.sta_lat;
                            item.name = item.terminal_name;
                            item.icon = getTerminalInfo(item.terminal_type)?.markIcon1;
                            return item;
                        })
                        this.mapLandDeviceSet(markerArr, 2);
                    }
                } else {
                    this.equipmentSituationData = [];
                    if (this.markerSearchValue !== "") {
                        this.mapLandDeviceSet([], 2);
                    }
                }
                this.equipmentLoading = false;
            });

        },
        /**
         * 获取区域数据
         */
        getAreaList() {
            let areaList = [];
            let params = { "areaId": tpSaaSCore.getUserDetails().areaId };
            tpHttp.post(this, "action=com.top.hsfpl.area.getAreaGeometry", { param: JSON.stringify(params) }, (data, code, message) => {
                if (code == 0 && data && data.coordinates && data.coordinates.length) {
                    areaList = data.coordinates[0];
                } else {
                    areaList = xkxBigJson;
                }
                let outer = [
                    new AMap.LngLat(-360, 90, true),
                    new AMap.LngLat(-360, -90, true),
                    new AMap.LngLat(360, -90, true),
                    new AMap.LngLat(360, 90, true)
                ];
                let path = [outer];
                path.push.apply(path, [areaList]);
                let polygon = new AMap.Polygon({
                    path: path,
                    strokeColor: '#00aeff',
                    strokeOpacity: 1,
                    strokeWeight: 2,
                    fillColor: '#000',
                    fillOpacity: 0.5,
                });
                this.exampleMap.add(polygon);

                polygon.on('click', (e) => {
                    if (this.infoWindow) this.infoWindow.close();
                    this.mapLandDeviceSet([], 2);
                });
            })
            let params2 = { region_code: tpSaaSCore.getUserDetails().areaId };
            tpHttp.post(this, "action=com.top.hsfpl.onePic.region.geom", { param: JSON.stringify(params2) }, (data, code, message) => {
                if (code == 0 && data && data.features && data.features.length) {
                    let polygonList = [];
                    const features = data.features;
                    for (let i = 0; i < features.length; i++) {
                        const { geometry, properties } = features[i];
                        let polygon = new AMap.Polygon({
                            path: geometry.coordinates,
                            fillColor: '#16c8cd',
                            strokeOpacity: 1,
                            fillOpacity: 0,
                            strokeWeight: 2,
                            strokeColor: '#00aeff',
                        });
                        polygonList.push(polygon);
                        polygon.on('click', (e) => {
                            if (this.infoWindow) this.infoWindow.close();
                            this.mapLandDeviceSet([], 2);
                        });
                    }
                    const overlayGroup = new AMap.OverlayGroup([...polygonList]);
                    this.exampleMap.add(overlayGroup);
                }
            })
        }
    },
    mounted() {
        this.initMap();
        // 头部 共预警次数
        bus.$on("problemHandleTotal", (value) => {
            this.problemHandleTotal = value;
        })
    }
};

